package com.zapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zapi.common.Result;
import com.zapi.entity.User;
import com.zapi.file.entity.FileInfo;
import com.zapi.file.service.FileService;
import com.zapi.mapper.UserMapper;
import com.zapi.service.UserService;
import com.zapi.util.JwtUtil;
import com.zapi.util.SealUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Controller
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private com.zapi.service.SystemStatisticsService systemStatisticsService;

    /**
     * 用户登录
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        try {
            
            // 创建认证token
            UsernamePasswordAuthenticationToken authToken = 
                new UsernamePasswordAuthenticationToken(username, password);
            
            // 进行认证
            Authentication authentication = authenticationManager.authenticate(authToken);
            
            if (authentication.isAuthenticated()) {
                // 获取用户详情
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                
                // 从数据库获取完整的用户信息
                User user = userService.findByUsername(userDetails.getUsername());
                if (user == null) {
                    return Result.error("用户信息不存在");
                }
                
                // 生成JWT token，使用实际的用户ID
                String token = jwtUtil.generateToken(user.getUsername(), user.getId());
                
                // 更新最后登录时间
                user.setLastLoginTime(java.time.LocalDateTime.now());
                userService.updateById(user);
                
                // 记录登录统计
                try {
                    systemStatisticsService.recordLogin();
                } catch (Exception e) {
                    // 统计失败不影响登录
                }
                
                // 构建返回数据
                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
                
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", user.getId());
                userInfo.put("username", user.getUsername());
                userInfo.put("realName", user.getRealName());
                userInfo.put("email", user.getEmail());
                userInfo.put("status", user.getStatus());
                userInfo.put("lastLoginTime", user.getLastLoginTime());
                userInfo.put("createTime", user.getCreateTime());
                userInfo.put("updateTime", user.getUpdateTime());
                
                data.put("user", userInfo);
                
                return Result.success(data);
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 临时方法：更新admin用户密码
     */
    @ApiOperation("更新admin用户密码")
    @PostMapping("/updatePassword")
    public Result<String> updatePassword() {
        try {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String newPassword = encoder.encode("123456");
            
            // 更新密码
            int result = userMapper.updatePasswordByUsername("admin", newPassword);
            
            if (result > 0) {
                return Result.success("密码更新成功，新密码: " + newPassword);
            } else {
                return Result.error("密码更新失败：未找到admin用户");
            }
        } catch (Exception e) {
            return Result.error("密码更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public Result<Page<User>> getUserList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String realName,
            @RequestParam(required = false) Integer status) {
        try {
            Page<User> page = new Page<>(current, size);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            
            // 添加关键词搜索条件（搜索用户名、真实姓名、邮箱）
            if (keyword != null && !keyword.trim().isEmpty()) {
                String searchKeyword = keyword.trim();
                queryWrapper.and(wrapper -> 
                    wrapper.like("username", searchKeyword)
                           .or().like("real_name", searchKeyword)
                           .or().like("email", searchKeyword)
                );
            }
            
            // 兼容旧的realName参数
            if (realName != null && !realName.trim().isEmpty()) {
                queryWrapper.like("real_name", realName.trim());
            }
            
            // 状态筛选
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            
            // 只查询未删除的用户
            queryWrapper.eq("deleted", 0);
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc("create_time");
            
            Page<User> result = userService.page(page, queryWrapper);
            
            // 清除返回结果中的密码字段
            result.getRecords().forEach(user -> user.setPassword(null));
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取用户列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户详情
     */
    @ApiOperation("获取用户详情")
    @GetMapping("/detail/{id}")
    public Result<User> getUserDetail(@PathVariable Long id) {
        try {
            User user = userService.getById(id);
            if (user == null || user.getDeleted() == 1) {
                return Result.error("用户不存在");
            }
            
            // 清除敏感信息
            user.setPassword(null);
            
            return Result.success(user);
        } catch (Exception e) {
            return Result.error("获取用户详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成用户默认头像
     * 
     * @param username 用户名
     * @param userId 用户ID
     * @return 头像文件ID
     */
    private String generateDefaultAvatar(String username, Long userId) {
        try {
            // 优先使用真实姓名，否则使用用户名
            // SealUtils.changfangx方法内部会自动限制为4个字符
            String displayName = username;
            if (displayName == null || displayName.trim().isEmpty()) {
                displayName = "用户";
            }
            
            // 使用SealUtils生成头像图片（使用方章样式）
            // 方法内部已限制最多4个字符
            BufferedImage avatarImage = SealUtils.sealFanz01(displayName.trim());
            
            // 将BufferedImage转换为InputStream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(avatarImage, "png", baos);
            InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
            
            // 保存头像文件
            String fileName = "avatar_" + userId + "_" + System.currentTimeMillis() + ".png";
            FileInfo avatarFile = fileService.uploadFile(
                inputStream, 
                fileName, 
                "avatar", 
                "用户默认头像", 
                userId, 
                username
            );
            
            // 返回头像文件ID（字符串格式），前端会使用 /file/download/{fileId} 接口预览
            return avatarFile.getId().toString();
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 添加用户
     */
    @ApiOperation("添加用户")
    @PostMapping("/add")
    public Result<String> addUser(@RequestBody User user) {
        try {
            // 检查用户名是否已存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", user.getUsername());
            queryWrapper.eq("deleted", 0);
            User existingUser = userService.getOne(queryWrapper);
            if (existingUser != null) {
                return Result.error("用户名已存在");
            }
            
            // 检查邮箱是否已存在
            if (user.getEmail() != null && !user.getEmail().trim().isEmpty()) {
                QueryWrapper<User> emailQuery = new QueryWrapper<>();
                emailQuery.eq("email", user.getEmail());
                emailQuery.eq("deleted", 0);
                User existingEmailUser = userService.getOne(emailQuery);
                if (existingEmailUser != null) {
                    return Result.error("邮箱已存在");
                }
            }
            
            // 加密密码
            if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                user.setPassword(encoder.encode(user.getPassword()));
            } else {
                return Result.error("密码不能为空");
            }
            
            // 设置默认值
            if (user.getStatus() == null) {
                user.setStatus(1); // 默认启用
            }
            user.setDeleted(0); // 未删除
            user.setCreateTime(java.time.LocalDateTime.now());
            user.setUpdateTime(java.time.LocalDateTime.now());
            
            boolean success = userService.save(user);
            if (success) {
                // 如果没有上传头像，自动生成默认头像
                if (user.getAvatar() == null || user.getAvatar().trim().isEmpty()) {
                    String avatarUrl = generateDefaultAvatar(user.getRealName(), user.getId());
                    if (avatarUrl != null) {
                        user.setAvatar(avatarUrl);
                        userService.updateById(user);
                    }
                }
                return Result.success("添加用户成功");
            } else {
                return Result.error("添加用户失败");
            }
        } catch (Exception e) {
            return Result.error("添加用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户
     */
    @ApiOperation("更新用户")
    @PutMapping("/update")
    public Result<String> updateUser(@RequestBody User user) {
        try {
            // 检查用户是否存在
            User existingUser = userService.getById(user.getId());
            if (existingUser == null || existingUser.getDeleted() == 1) {
                return Result.error("用户不存在");
            }
            
            // 如果修改了用户名，检查是否与其他用户重复
            if (!existingUser.getUsername().equals(user.getUsername())) {
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("username", user.getUsername());
                queryWrapper.eq("deleted", 0);
                queryWrapper.ne("id", user.getId());
                User duplicateUser = userService.getOne(queryWrapper);
                if (duplicateUser != null) {
                    return Result.error("用户名已存在");
                }
            }
            
            // 如果修改了邮箱，检查是否与其他用户重复
            if (user.getEmail() != null && !user.getEmail().equals(existingUser.getEmail())) {
                QueryWrapper<User> emailQuery = new QueryWrapper<>();
                emailQuery.eq("email", user.getEmail());
                emailQuery.eq("deleted", 0);
                emailQuery.ne("id", user.getId());
                User duplicateEmailUser = userService.getOne(emailQuery);
                if (duplicateEmailUser != null) {
                    return Result.error("邮箱已存在");
                }
            }
            
            // 保留原有的密码和创建时间
            user.setPassword(existingUser.getPassword());
            user.setCreateTime(existingUser.getCreateTime());
            user.setUpdateTime(java.time.LocalDateTime.now());
            
            // 如果没有头像且之前也没有，自动生成默认头像
            if ((user.getAvatar() == null || user.getAvatar().trim().isEmpty()) && 
                (existingUser.getAvatar() == null || existingUser.getAvatar().trim().isEmpty())) {
                String avatarUrl = generateDefaultAvatar(user.getRealName(), user.getId());
                if (avatarUrl != null) {
                    user.setAvatar(avatarUrl);
                }
            } else if (user.getAvatar() == null || user.getAvatar().trim().isEmpty()) {
                // 保留原有头像
                user.setAvatar(existingUser.getAvatar());
            }
            
            boolean success = userService.updateById(user);
            if (success) {
                return Result.success("更新用户成功");
            } else {
                return Result.error("更新用户失败");
            }
        } catch (Exception e) {
            return Result.error("更新用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量生成用户默认头像（临时接口，用于测试）
     */
    @ApiOperation("批量生成用户默认头像")
    @PostMapping("/generateAvatars")
    public Result<String> generateAvatarsForAllUsers() {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("deleted", 0);
            queryWrapper.and(wrapper -> wrapper.isNull("avatar").or().eq("avatar", ""));
            
            List<User> usersWithoutAvatar = userService.list(queryWrapper);
            
            int successCount = 0;
            int failCount = 0;
            
            for (User user : usersWithoutAvatar) {
                try {
                    String displayName = user.getRealName() != null && !user.getRealName().trim().isEmpty() 
                        ? user.getRealName() 
                        : user.getUsername();
                    
                    String avatarUrl = generateDefaultAvatar(displayName, user.getId());
                    if (avatarUrl != null) {
                        user.setAvatar(avatarUrl);
                        userService.updateById(user);
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                    e.printStackTrace();
                }
            }
            
            return Result.success(String.format("批量生成完成！成功: %d, 失败: %d", successCount, failCount));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量生成头像失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户状态
     */
    @ApiOperation("更新用户状态")
    @PutMapping("/updateStatus/{id}")
    public Result<String> updateUserStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            // 检查用户是否存在
            User existingUser = userService.getById(id);
            if (existingUser == null || existingUser.getDeleted() == 1) {
                return Result.error("用户不存在");
            }
            
            // 更新状态
            existingUser.setStatus(status);
            boolean success = userService.updateById(existingUser);
            if (success) {
                String statusText = status == 1 ? "启用" : "禁用";
                return Result.success(statusText + "用户成功");
            } else {
                return Result.error("更新用户状态失败");
            }
        } catch (Exception e) {
            return Result.error("更新用户状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteUser(@PathVariable Long id) {
        try {
            // 检查用户是否存在
            User existingUser = userService.getById(id);
            if (existingUser == null || existingUser.getDeleted() == 1) {
                return Result.error("用户不存在");
            }
            
            // 逻辑删除
            existingUser.setDeleted(1);
            boolean success = userService.updateById(existingUser);
            if (success) {
                return Result.success("删除用户成功");
            } else {
                return Result.error("删除用户失败");
            }
        } catch (Exception e) {
            return Result.error("删除用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有启用用户
     */
    @ApiOperation("获取所有启用用户")
    @GetMapping("/enabled")
    public Result<java.util.List<User>> getEnabledUsers() {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            
            // 只查询启用状态的用户
            queryWrapper.eq("status", 1);
            
            // 只查询未删除的用户
            queryWrapper.eq("deleted", 0);
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc("create_time");
            
            java.util.List<User> users = userService.list(queryWrapper);
            
            // 清除返回结果中的密码字段
            users.forEach(user -> user.setPassword(null));
            
            return Result.success(users);
        } catch (Exception e) {
            return Result.error("获取启用用户列表失败：" + e.getMessage());
        }
    }
} 